<?php
/**
 * Created by PhpStorm.
 * User: PHP
 * Date: 2018/2/27
 * Time: 10:57
 */

namespace app\admin\controller;
use app\admin\model\Shop;
use app\admin\model\Terminal;
use app\admin\model\TransactionRecord;

class Branch extends Base
{
    /**
     * 分润列表
     *
     * @return mixed
     * @author   [小码哥]
     */
    public function index()
    {
        if (request()->isPost()) {
            return json(['code' => 0, 'data' => null, 'count' => 0, 'msg' => '分润列表']);
        }
        return $this->fetch();
    }

    /**
     * 导入
     * @return mixed|\think\response\Json
     * @throws \PHPExcel_Reader_Exception
     * @author   [小码哥]
     */
    public function import()
    {
        if (request()->isPost()) {
            $param = input('post.');


            error_reporting(E_ALL);
            ini_set('display_errors', true);
            ini_set('display_startup_errors', true);
            define('EOL', (PHP_SAPI == 'cli') ? PHP_EOL : '<br />');
            date_default_timezone_set('Europe/London');

            /** Include PHPExcel_IOFactory */
            require_once ROOT_PATH . 'extend/Classes/PHPExcel/IOFactory.php';

            // $inputFileName = ROOT_PATH . "mpos2.xls";
            $inputFileName = $param['filename'];

            if (!file_exists($inputFileName)) {
                return json(['code' => 0, 'data' => null, 'msg' => '文件不存在']);
            }

            $inputFileType = \PHPExcel_IOFactory::identify($inputFileName);
            $objReader = \PHPExcel_IOFactory::createReader($inputFileType);

            $sheetList = $objReader->listWorksheetNames($inputFileName);
            $sheetInfo = $objReader->listWorksheetInfo($inputFileName);
            $PHPExcel = $objReader->load($inputFileName); // 载入excel文件
            switch (strtoupper($param['brand'])) {
                case 'LAKALA':
                    $newArray = $this->LAKALAExcel($PHPExcel, $sheetInfo);
                    break;
                case 'YOUSHUA':
                    $newArray = $this->YOUSHUAExcel($PHPExcel, $sheetInfo);
                    break;
            }

            if (empty($newArray) || !is_array($newArray)) {
                return json(['code' => 0, 'data' => null, 'msg' => '读取出错']);
            }
            cache('param', json_encode($newArray));

            @unlink($inputFileName);

            $param = $this->fetch('import_param', ['data' => $newArray]);
            return json(['code' => 200, 'data' => $param, 'msg' => '读取成功']);
        }
        $data = cache('param');
        if ($data) {
            $data = json_decode($data, true);
        }
        $this->send_date($data);
        $this->assign('data', $data);
        return $this->fetch();
    }

    /**
     * 清除记录
     * @author   [小码哥]
     */
    public function clears()
    {
        cache('param', null);
        return json(['code' => 200, 'data' => null, 'msg' => '清除成功']);
    }

    /**
     * 拉卡拉
     * @param $PHPExcel
     * @param array $sheetInfo
     * @return array|bool
     * @author   [小码哥]
     */
    public function LAKALAExcel($PHPExcel, $sheetInfo = [])
    {
        if (empty($sheetInfo) || !$PHPExcel)
            return false;
        $newArray = [];
        foreach ($sheetInfo as $key => $value) {
            $sheet = $PHPExcel->getSheet($key); // 读取第 $key 个工作表
            $totalRows = $sheet->getHighestRow(); // 取得总行数
            $totalColumns = $sheet->getHighestColumn(); // 取得总列数
            $keys = [
                'E' => 'shop_num',
                'F' => 'shop_name',
                'G' => 'zhong_duan',
                'H' => 'jiaoyi_date',
                'I' => 'jiaoyi_money',
                'J' => 'jiaoyi_shouxu',
                'K' => 'card_type',
                'L' => 'pay_date',
                'M' => 'type'
            ];
            for ($row = 2; $row <= $totalRows; $row++) {
                for ($column = 'E'; $column <= $totalColumns; $column++) {
                    $rowVal = $sheet->getCell($column . $row)->getValue();
                    if (isset($keys[$column])) {
                        switch ($column) {
                            case 'H':
                                $rowArray[$keys[$column]] = $rowVal;
                                $rowArray['jiaoyi_shouxu'] = 0;
                            case 'L':
                                $rowArray[$keys[$column]] = strtotime($rowVal);
                                $rowArray['pay_date'] = strtotime($rowVal);
                                break;
                            default:
                                $rowArray[$keys[$column]] = $rowVal;
                                break;
                        }
                        $newArray[$row] = $rowArray;
                    }
                }
            }
        }
        return $newArray;
    }


    /**
     * 友刷
     * @param $PHPExcel
     * @param array $sheetInfo
     * @return array|bool
     * @author   [小码哥]
     */
    public function YOUSHUAExcel($PHPExcel, $sheetInfo = [])
    {
        if (empty($sheetInfo) || !$PHPExcel)
            return false;
        $newArray = [];
        foreach ($sheetInfo as $key => $value) {
            $sheet = $PHPExcel->getSheet($key); // 读取第 $key 个工作表
            $totalRows = $sheet->getHighestRow(); // 取得总行数
            $totalColumns = $sheet->getHighestColumn(); // 取得总列数
            $keys = [
                'B' => 'type',
                'C' => 'shop_num',
                'D' => 'shop_name',
                'F' => 'zhong_duan',
                'J' => 'jiaoyi_money',
                'L' => 'jiaoyi_date',
                'H' => 'card_type',
            ];
            for ($row = 2; $row <= $totalRows; $row++) {
                for ($column = 'B'; $column <= $totalColumns; $column++) {
                    $rowVal = $sheet->getCell($column . $row)->getValue();
                    if (isset($keys[$column])) {
                        switch ($column) {
                            case 'J':
                                $rowArray[$keys[$column]] = $rowVal;
                                $rowArray['jiaoyi_shouxu'] = 0;
                                break;
                            case 'L':
                                $rowArray[$keys[$column]] = strtotime($rowVal);
                                $rowArray['pay_date'] = strtotime($rowVal);
                                break;
                            default:
                                $rowArray[$keys[$column]] = $rowVal;
                                break;
                        }
                        $newArray[$row] = $rowArray;
                    }
                }
            }
        }
        return $newArray;
    }
    //把数据写入数据库
    public function send_date($data){

        if(!$data) return json(['code' => 0, 'data' => $data, 'msg' => '数据为空']);
        //循环插入
        $is_error = false;
        foreach($data as $k=>$v){
            //判断商户是否存在
            $is_shop = Shop::where('shop_number',$v['shop_num'])->find();
            if(!$is_shop){
                $re_shop=Shop::create([
                    'shop_number'=>$v['shop_num'],
                    'shop_name'=>$v['shop_name']
                ]);
            }
            //判断终端是否存在
            $is_ter  =  Terminal::where('terminal_number',$v['zhong_duan'])->find();
            if(!$is_ter){
                $re_ter = Terminal::create([
                    'terminal_number'=>$v['zhong_duan'],
                    'type'=>$v['type']
                ]);
            }

            //查询是否重复
               $is_count =  TransactionRecord::where('terminal_number',$v['zhong_duan'])
                    ->where('pay_date',$v['pay_date'])
                    ->where('trading_date',$v['jiaoyi_date'])
                    ->count();
            if(!$is_count){
                $re = TransactionRecord::create([
                    'terminal_number'=>$v['zhong_duan']??'',//终端号
                    'shop_number'=>$v['shop_num']??'',//商户号
                    'card_type'=>$v['card_type']??'',//卡类型
                    'trading_date' => $v['jiaoyi_date']??null,//交易时间
                    'trading_money'=>$v['jiaoyi_money']??0,//交易金额
                    'service_money'=>$v['jiaoyi_shouxu']??0,//手续费
                    'pay_date'=>$v['pay_date']??null,//支付时间
                ]);
                if(!$re) $is_error = true;
            }


        }
        if($is_error) return json(['code' => 0, 'data' => '', 'msg' => '存储出现错误']);
    }



}